package co.chuangdian.oflauncher.widgets.system;

import java.util.List;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.IBinder;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import cn.onekit.android.ACTIVITY;
import co.chuangdian.oflauncher.MainActivity;
import co.chuangdian.oflauncher.R;
import co.chuangdian.oflauncher.widgets.system.MusicPlayerService.MusicBinder;
import uc.NoScrollListView;

public class MusicPlayWidget extends LinearLayout implements View.OnClickListener, OnItemClickListener {

	private TextView mAuthorName;
	private ImageView mMusicIcon;
	private ImageView mMusicPre = null;
	private ImageView mMusicPlay = null;
	private ImageView mMusicNext = null;
	private int musicNum = 0;
	private List<Music> list;
	private String albumArt;
	public boolean isAutoNext = false;
	private MusicPlayerService.MusicBinder music_binder;
	private MusicPlayerService mService;
	private boolean is_Pause = false;
	private NoScrollListView mListView;
	public boolean isShowing = true;
	private Context context;
	private SeekBar sb;
	private NextMusicReceiver receiver;
	private MusicServiceConnection connection;

	public MusicPlayWidget(Context context) {
		super(context);
		this.context = context;
		init();
	}

	private void bindMusicService() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("co.chuangdian.launcher.NextMusicReceiver");

		filter.addAction("co.chuangdian.launcher.CurrentPositionReceiver");
		receiver = new NextMusicReceiver();
		context.registerReceiver(receiver, filter);

		connection = new MusicServiceConnection();
		Intent intent = new Intent(context, MusicPlayerService.class);
		context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
	}

	private void init() {
		MainActivity.musicPlayWidgetFragment = this;
		View v = View.inflate(context, R.layout.widget_musicplayer, this);
		mAuthorName = (TextView) v.findViewById(R.id.frag_music_author);

		mMusicIcon = (ImageView) v.findViewById(R.id.frag_music_icon);
		mMusicIcon.setOnClickListener(this);

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 8;
		options.inJustDecodeBounds = false;
		sb = (SeekBar) v.findViewById(R.id.sb);
		sb.setOnSeekBarChangeListener(seekBarChangeListener);

		mAuthor = (TextView) v.findViewById(R.id.music_author);

		mMusicPre = (ImageView) v.findViewById(R.id.frag_music_pre);
		mMusicPre.setOnClickListener(this);

		mMusicPlay = (ImageView) v.findViewById(R.id.frag_music_play);
		mMusicPlay.setOnClickListener(this);

		mMusicNext = (ImageView) v.findViewById(R.id.frag_music_next);
		mMusicNext.setOnClickListener(this);

		mListView = (NoScrollListView) v.findViewById(R.id.music_listview);
		LayoutParams params = (LayoutParams) mListView.getLayoutParams();
		list = MusicList.getInstance(context).getMusicList();
		
		mListView.setLayoutParams(params);

		if (list != null && list.size() > 0) {
			musicNum = 0;
			updateMusicInfo();
			if (list.size() >= 4) {
				params.height = ACTIVITY.dp2px(174);
			} else {
				params.height = LayoutParams.WRAP_CONTENT;
			}
		}
		bindMusicService();
	}

	private String getAlbumArt(int album_id) {
		String mUriAlbums = "content://media/external/audio/albums";
		String[] projection = new String[] { "album_art" };
		Cursor cur = context.getContentResolver().query(Uri.parse(mUriAlbums + "/" + Integer.toString(album_id)),
				projection, null, null, null);
		String album_art = null;
		if (cur.getCount() > 0 && cur.getColumnCount() > 0) {
			cur.moveToNext();
			album_art = cur.getString(0);
		}
		cur.close();
		cur = null;
		return album_art;
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.frag_music_pre:
			if (checkExistMusic()) {
				pre();
			}

			break;
		case R.id.frag_music_play:
			if (mService != null && checkExistMusic()) {
				if (mService.isMusicPlaying()) {
					// 当音乐正在播放，点击播放按钮，暂停
					pause();
					is_Pause = true;
				} else {
					// 当音乐未播放，点击播放按钮，播放
					if (is_Pause) {
						replay();
					} else {
						play();
					}
				}
			}

			break;
		case R.id.frag_music_next:
			next();

			break;
		/*case R.id.frag_music_icon:
			if (isShowing) {
				mListView.setVisibility(View.VISIBLE);
				adapter = new MusicAdapter(context, list);
				mListView.setAdapter(adapter);
				mListView.setOnItemClickListener(this);
				isShowing = false;

			} else {
				mListView.setVisibility(View.GONE);
				isShowing = true;
			}
			break;*/
		default:
			break;
		}
	}

	private void replay() {
		if (mService != null) {
			mService.replay();
			mMusicPlay.setImageResource(R.drawable.btn_music_pause);
			updateMusicInfo();
		}
	}

	private void pause() {
		if (mService != null) {
			mService.pause();
			mMusicPlay.setImageResource(R.drawable.btn_music_play);
			updateMusicInfo();
		}
	}

	private boolean checkExistMusic() {
		if (list == null || list.size() <= 0) {
			Toast.makeText(context, "当前没有音乐可以播放", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	private void pre() {
		if (mService != null) {
			if (musicNum > 0) {
				musicNum = musicNum - 1;
				mService.play(musicNum);
				updateMusicInfo();
				mMusicPlay.setImageResource(R.drawable.btn_music_pause);
			} else {
				musicNum = list.size() - 1;
				mService.play(musicNum);
				updateMusicInfo();
				mMusicPlay.setImageResource(R.drawable.btn_music_pause);
			}
			//select(musicNum);
		}
	}

	private void play() {
		if (mService != null) {
			mService.play(musicNum);
			updateMusicInfo();
			mMusicPlay.setImageResource(R.drawable.btn_music_pause);
		}
	}

	private void next() {
		if (mService != null) {
			if (musicNum < list.size() - 1) {
				musicNum = musicNum + 1;
				mService.play(musicNum);
				updateMusicInfo();
				mMusicPlay.setImageResource(R.drawable.btn_music_pause);
			} else {
				musicNum = 0;
				if (isAutoNext == true) {
					mService.stop();
					mMusicPlay.setImageResource(R.drawable.btn_music_play);
					isAutoNext = false;
				} else {
					mMusicPlay.setImageResource(R.drawable.btn_music_pause);
					mService.play(musicNum);
				}
				//select(musicNum);
				updateMusicInfo();
			}
		}
	}

	private void updateMusicInfo() {
		mAuthorName.setText(list.get(musicNum).getTitle());
		mAuthor.setText(list.get(musicNum).getSinger());
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inSampleSize = 8;
		options.inJustDecodeBounds = false;
		// Bitmap bitmap;
		albumArt = getAlbumArt(list.get(musicNum).getAlbumId()); // icon
		if (albumArt == null) {
			mMusicIcon.setImageResource(R.drawable.music_default_icon);
			// bitmap = BitmapFactory.decodeResource(getResources(),
			// R.drawable.music_default_icon, options);
		} else {
			Bitmap bm = BitmapFactory.decodeFile(albumArt);
			mMusicIcon.setImageBitmap(bm);
			// bitmap = BitmapFactory.decodeFile(albumArt, options);
		}
	}

	public class NextMusicReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals("co.chuangdian.launcher.NextMusicReceiver")) {
				isAutoNext = true;
				next();
			} else if (intent.getAction().equals("co.chuangdian.launcher.CurrentPositionReceiver")) {

				int duration = intent.getIntExtra("duration", 0);
				int currentPosition = intent.getIntExtra("currentPosition", 0);
				sb.setMax(duration);
				sb.setProgress(currentPosition);
			}

		}

	}

	OnSeekBarChangeListener seekBarChangeListener = new OnSeekBarChangeListener() {
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			// 根据拖动的进度改变音乐播放进度
			int progress = seekBar.getProgress();
			// 改变播放进度
			music_binder.getService().seekTo(progress);
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		}
	};
	private TextView mAuthor;

	public void onDestroy() {
		context.unbindService(connection);

		context.unregisterReceiver(receiver);

	};

	class MusicServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder binder) {
			music_binder = (MusicBinder) binder;
			if (music_binder != null) {
				mService = music_binder.getService();
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {

		}

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (mService != null) {
			musicNum = position;
			mService.play(musicNum);
			updateMusicInfo();
			mMusicPlay.setImageResource(R.drawable.btn_music_pause);
		}
		//mListView.setVisibility(View.GONE);
		isShowing = true;
		// WidgetListRow.setMusicChecked(isShowing);
	}

	/**
	 * 设置歌曲列表的显示和隐藏
	 * 
	 */

	public void setVisible(boolean bool) {
		isShowing = bool;
		if (isShowing) {
			mListView.setVisibility(View.GONE);
		} else {
			mListView.setVisibility(View.VISIBLE);
			// mListView.requestDisallowInterceptTouchEvent(true);
			MusicAdapter adapter = new MusicAdapter(context, list);
			mListView.setAdapter(adapter);
			mListView.setOnItemClickListener(this);
		}

		// isShowing = !isShowing;
	}
}
